package org.oy.sealogger.ds;

import java.util.Observable;

import org.apache.log4j.Logger;
import org.oy.sealogger.common.Config;
import org.oy.sealogger.common.Messages;
import org.oy.sealogger.device.Device;
import org.oy.sealogger.device.DeviceException;

/**
 * Superclass for all types of data source
 * @author riku
 *
 */
public abstract class DataSource extends Observable implements Runnable {

	public static enum State { OK, ERROR, UNKNOWN }
	
	protected static Logger log = Config.getLogger();

	protected Device device;
	protected State state = null;
	
	protected boolean terminateOnError = false;

	/**
	 * Attaches a device to the data source. If a device has already been attached,
	 * the method will try to disconnect the existing one first. If disconnection is successful,
	 * the device will be replaced.
	 * @param d
	 */
	public boolean attach(Device d) {
		if(device != null) {
			try {
				device.disconnect();
			} catch(DeviceException e) {
				log.error(Messages.getMessage("error.cannot_disconnect"));
				return false;
			}			
		}
		
		this.device = d;
		return true;
	}
	
	public State getState() {
		return state == null ? State.UNKNOWN : state;
	}
	
	/**
	 * This method is called when a complete row has been read from the input stream
	 * and is ready to be delivered.
	 * @param rawData
	 */
	protected synchronized final void deliver(String rawData) {
		setChanged();
		notifyObservers(rawData);
	}

}
